package com.witmore.skyline.web.config;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import jakarta.annotation.PostConstruct;
import java.util.UUID;

@Slf4j
@Configuration
public class MqttConfig {

    @Value("${mqtt.broker-url}")
    private String brokerUrl;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    // Neutron 业务配置
    @Value("${mqtt.neutron.client-id}")
    private String neutronClientId;
    @Value("${mqtt.neutron-topic}")
    private String neutronMsgTopic;

    // WeChat 业务配置
    @Getter
    @Value("${mqtt.wechat.client-id}")
    private String wechatClientId;
    @Getter
    @Value("${mqtt.wechat-topic}")
    private String wechatTopic;

    public String buildNeutronTopic(String orgId) {
        // 替换 %s
        return String.format(neutronMsgTopic, orgId);
    }

    @PostConstruct
    public void init() {
        neutronClientId = String.format(neutronClientId, UUID.randomUUID());
        wechatClientId = String.format(wechatClientId, UUID.randomUUID());

        log.info("MQTT neutron connecting to: {}, clientId: {}", brokerUrl, neutronClientId);
        log.info("MQTT wechat connecting to: {}, clientId: {}", brokerUrl, wechatClientId);
    }

    // 创建公共的 MQTT 客户端工厂
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{brokerUrl});
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        factory.setConnectionOptions(options);
        return factory;
    }

    // ================================== Neutron 业务配置 ==================================
    // 配置出站通道（用于发送消息）
    @Bean
    public MessageChannel neutronOutboundChannel() {
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = "neutronOutboundChannel")
    public MessageHandler neutronOutbound() {
        MqttPahoMessageHandler handler = new MqttPahoMessageHandler(neutronClientId + "-producer", mqttClientFactory());
        handler.setAsync(true);
        return handler;
    }


    // ================================== WeChat 业务配置 ==================================
    // 配置出站通道（用于发送消息）
    @Bean
    public MessageChannel wechatOutboundChannel() {
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = "wechatOutboundChannel")
    public MessageHandler wechatOutbound() {
        MqttPahoMessageHandler handler = new MqttPahoMessageHandler(wechatClientId + "-producer", mqttClientFactory());
        handler.setAsync(true);
        return handler;
    }

    // 配置入站通道（用于接收消息）
    @Bean
    public MessageChannel wechatInboundChannel() {
        return new DirectChannel();
    }

    @Bean
    public MqttPahoMessageDrivenChannelAdapter wechatInbound() {
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                wechatClientId + "-consumer", mqttClientFactory(), wechatTopic);
        adapter.setOutputChannel(wechatInboundChannel());
        return adapter;
    }
}